<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%@ page import="java.io.File" %>
<%@ page import="org.apache.commons.fileupload.FileItemFactory" %>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%@ page import="java.util.List" %>
<%@ page import="org.apache.commons.fileupload.FileUpload" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="org.apache.commons.fileupload.FileItem" %>
<%@ page import="java.net.URLEncoder" %><%--
  Created by IntelliJ IDEA.
  User: aiwzy
  Date: 2022/4/7
  Time: 10:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>对文件进行上传操作</title>
</head>
<body>
<%
    boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
    System.out.println(isMultipartContent);
    String path ="D:\\web_project\\src\\main\\webapp\\images";

    File file = new File(path);

    if(!file.exists()){
        file.mkdir();
    }
    System.out.println(file);
    if(isMultipartContent){
        FileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
        List<FileItem> list = servletFileUpload.parseRequest(request);

        String title =null;
        Iterator<FileItem> iterator = list.iterator();
        while(iterator.hasNext()){
            FileItem item = iterator.next();
            boolean isfield = item.isFormField();
            if(isfield){
                String fieldName = item.getFieldName();
                if (fieldName.equals("title")){
                    title = item.getString("utf-8");
                }
            }else {
                String fileUpload = URLEncoder.encode(item.getName(),"utf-8");
                //将图片转化为文件对象
                File file1 = new File(fileUpload);
                if(file1.getName()!=null && !file1.getName().equals("")){
                    File file2 = new File(path,file1.getName());

                    item.write(file2);

                }



            }
            
        }
    }



%>

</body>
</html>
